# print("发件人: ", message.SenderName)
# print("发件人邮箱: ", message.SenderEmailAddress)
# print("发送时间: ", message.SentOn)
# print("接收时间: ", message.ReceivedTime)
# print("收件人: ", message.To)
# print("抄送: ", message.CC)
# print("主题: ", message.Subject)
# print("正文: ", message.Body)

from datetime import datetime
import os.path
import sys
import win32timezone
import pandas as pd

from common import common
import win32com.client


class GetOutlookData():
    def __init__(self, zd):
        self.zd = zd
        self.dfs = pd.DataFrame()
        self.path = [os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '邮件附件'),
                     os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '提取的汇总文件')]
        common.create_folder_if_not_exists(self.path)

    def get_data(self):
        # 启动Outlook应用
        outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
        # 通过文件夹名获取文件夹，例如收件箱可以使用"6"
        inbox = outlook.GetDefaultFolder(6)
        self.traverse_folders(inbox)
        if self.dfs.empty:
            common.show_message("没有邮件", 1)
        else:
            self.dfs.to_excel(os.path.join(self.path[1],
                                           f'{self.zd['rad']}({str(self.zd['dateS'].strftime("%Y-%m-%d %H%M%S"))}-{str(self.zd['dateE'].strftime("%Y-%m-%d %H%M%S"))}).xlsx'),
                              index=False)

    def traverse_folders(self, folder):
        try:
            messages = folder.Items
            for message in messages:
                # 判断接收时间
                outlook_time = datetime.strptime(message.ReceivedTime.strftime("%Y-%m-%d %H:%M:%S"),
                                                 "%Y-%m-%d %H:%M:%S")
                if self.zd['dateS'] <= outlook_time <= self.zd['dateE']:
                    # 判断邮件主题
                    if self.zd['rad'] in message.Subject:
                        attachments = message.Attachments
                        if attachments.Count > 0:
                            for attachment in attachments:  # 对于附件，需要进行遍历
                                # 判断是不是以xlsx结尾的附件
                                if (attachment.FileName.endswith(".xls")) or (
                                        attachment.FileName.endswith(".xlsx")):
                                    savepath = os.path.join(self.path[0], attachment.FileName)
                                    attachment.SaveAsFile(savepath)
                                    df = pd.read_excel(savepath)
                                    if not df.empty:
                                        df['收件时间'] = str(outlook_time)
                                        self.dfs = pd.concat([self.dfs, df])
        except Exception as e:
            print(e)
            # common.show_message(e, 0)

        # 递归遍历子文件夹
        subfolders = folder.Folders
        for subfolder in subfolders:
            self.traverse_folders(subfolder)
